package net.fdukedom.epicurus.core.extensions.menu;

import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.resource.ResourceDispatcher;

import java.text.MessageFormat;
import java.text.FieldPosition;
import java.util.HashMap;
import java.util.Map;

/**
 * Adds Login|Logout item to menu
 *
 * @author Dmitry Y. Kochelaev
 */
public class LoginExtension extends MenuExtensionHandler {

    private ResourceDispatcher resourceDispatcher = ResourceDispatcher.getInstance();

    private String loginTitle = resourceDispatcher.getBundledValue("bundles.core.Extensions", "core.login.title");

    private String loginLink = resourceDispatcher.getBundledValue("bundles.core.Extensions", "core.login.actionLink");

    private MessageFormat logoutTitle = new MessageFormat(resourceDispatcher.getBundledValue("bundles.core.Extensions", "core.logout.title"));

    private String logoutLink = resourceDispatcher.getBundledValue("bundles.core.Extensions", "core.logout.actionLink");

    public Map<String, Object> execute(Map<String, Object> parameters) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put(IS_EXTENSION_VISIBLE, true);

        if (((Boolean) parameters.get("isLoggedIn"))) {
            result.put(EXTENSION_TITLE, logoutTitle.format(new Object[]{((User) parameters.get("user")).getName()}, new StringBuffer(), new FieldPosition(0)).toString());
            result.put(EXTENSION_ACTION, logoutLink);
        } else {
            result.put(EXTENSION_TITLE, loginTitle);
            result.put(EXTENSION_ACTION, loginLink);
        }
        return result;
    }

    public String getPresentation() {
        return "";
    }
}
